package com.zhangxin.aiInterview.manager.disruptor.strategy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhangxin.aiInterview.manager.disruptor.WsEvent;
import com.zhangxin.aiInterview.manager.xfapi.websocket.llmmodel.LLmWs;
import com.zhangxin.aiInterview.manager.xfapi.websocket.llmmodel.LLmWsManager;
import com.zhangxin.aiInterview.manager.xfapi.websocket.llmmodel.model.RoleContent;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.UUID;

/**
 * ws发送文字获取合成文本策略
 */
@Slf4j
//@Component
@Data
@Deprecated
public class LLmWsSendMsg implements WsSendMsg{
    @Value("${xunfei.appid}")
    public String appid;
    //使用的大模型
    @Value("${xunfei.llm.domain}")
    public String domain;

    @Override
    public void sendMessage(WsEvent wsEvent) {
        //获取当前用户的websocket连接
        WebSocket webSocket = LLmWsManager.getConnection(wsEvent.getUserId());
        //发送消息
        JSONObject requestJson=new JSONObject();
        // header参数
        JSONObject header=new JSONObject();
        header.put("app_id",appid);
        header.put("uid", UUID.randomUUID().toString().substring(0, 10));
        // parameter参数
        JSONObject parameter=new JSONObject();
        JSONObject chat=new JSONObject();
        chat.put("domain",domain);
        chat.put("temperature",0.5);
        chat.put("max_tokens",4096);
        parameter.put("chat",chat);
        // payload参数
        JSONObject payload=new JSONObject();
        JSONObject message=new JSONObject();
        JSONArray text=new JSONArray();
        //历史对话上下文获取
        List<RoleContent> historyList = LLmWs.historyMap.get(wsEvent.getUserId());
        if(!historyList.isEmpty()){
            for(RoleContent tempRoleContent:historyList){
                text.add(JSON.toJSON(tempRoleContent));
            }
        }
        // 最新问题
        RoleContent roleContent = new RoleContent();
        roleContent.setRole("user");
        roleContent.setContent(wsEvent.getUserContent());
        text.add(JSON.toJSON(roleContent));
        historyList.add(roleContent);

        message.put("text",text);
        payload.put("message",message);

        requestJson.put("header",header);
        requestJson.put("parameter",parameter);
        requestJson.put("payload",payload);
        //发送消息
        webSocket.send(requestJson.toString());
        log.info("发送消息：{}",requestJson);
    }
}
